package com.tengfei.main.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author feige
 * @version v1.0
 * @date 2022-09-16-10:09
 * @description
 */

@Configuration
public class RabbitMQConfig {

    // 延迟队列配置
    // 延迟队列名称
    public static final String DELAY_QUEUE = "delay.queue";
    // 延迟交换机
    public static final String DELAY_EXCHANGE = "delay.exchange";
    // 延迟路由键
    public static final String DELAY_ROUTING_KEY = "delay.routing.key";

    /**
     * 声明一个延迟队列
     *
     * @return
     */
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable(DELAY_QUEUE).build();
    }

    /**
     * 声明一个延迟交换机
     * CustomExchange为RabbitMQ插件所带
     *
     * @return
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_EXCHANGE, "x-delayed-message", true, false, args);
    }

    /**
     * 将延迟队列绑定到延迟交换机通过延迟路由键
     *
     * @param delayQueue
     * @param delayExchange
     * @return
     */
    @Bean
    public Binding delayBind(Queue delayQueue, CustomExchange delayExchange) {
        return BindingBuilder.bind(delayQueue).to(delayExchange).with(DELAY_ROUTING_KEY).noargs();
    }

}
